// components/electrons/useVerticalLabel.js
import { useState, useCallback, useRef } from 'react';

/**
 * Custom hook to manage the vertical label display
 * 
 * @returns {Object} The hook object
 * @returns {string} hook.activeLabel - Currently active label
 * @returns {boolean} hook.isLabelVisible - Whether the vertical label should be visible
 * @returns {Function} hook.getFieldProps - Function to get props for TextField components
 */
const useVerticalLabel = () => {
  const [activeLabel, setActiveLabel] = useState('');
  const [isLabelVisible, setIsLabelVisible] = useState(false);
  const timeoutRef = useRef(null);

  // Clear any existing timeouts
  const clearTimeouts = () => {
    if (timeoutRef.current) {
      clearTimeout(timeoutRef.current);
      timeoutRef.current = null;
    }
  };

  // Handle focus on a field
  const handleFocus = useCallback((event, label) => {
    clearTimeouts();
    setActiveLabel(label);
    setIsLabelVisible(true);
  }, []);

  // Handle blur (losing focus) on a field
  const handleBlur = useCallback(() => {
    clearTimeouts();
    // Add a small delay to prevent flickering when moving between fields
    timeoutRef.current = setTimeout(() => {
      setIsLabelVisible(false);
    }, 50);
  }, []);

  // Generate props to spread onto a TextField component
  const getFieldProps = useCallback((label) => {
    return {
      onFocus: (e) => handleFocus(e, label),
      onBlur: handleBlur
    };
  }, [handleFocus, handleBlur]);

  return {
    activeLabel,
    isLabelVisible,
    getFieldProps
  };
};

export default useVerticalLabel;